package com.zihan.task;

import com.zihan.domain.entity.Activity;
import com.zihan.service.IActivityService;
import com.zihan.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class CheckActivityStatus {

    @Resource
    private IActivityService activityService;
    @Resource
    private AliOssUtil aliOssUtil;

    // 每隔一分钟检查所有进行中的活动是否到了结束时间，并且修改活动状态
    @Scheduled(cron = "0 * * * * ?")
    public void checkActivityStatus() {
        log.info("开始检查活动状态");
        List<Activity> list = activityService.lambdaQuery()
                .eq(Activity::getStatus, 1)
                .list();
        List<Activity> res = list.stream()
                .filter(activity -> activity.getEndTime().isBefore(LocalDateTime.now()))
                .peek(activity -> activity.setStatus(2))
                .collect(Collectors.toList());
        if (!res.isEmpty()) {
            for (Activity activity : res) {
                aliOssUtil.generateAndUpload(activity.getId());
            }
            activityService.updateBatchById(res);
            log.info("检查活动状态，共更新 {} 条记录", res.size());
        }
    }
}
